package com.wxproj.wxai.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.wxproj.wxai.Constants.ConstantKey;
import com.wxproj.wxai.entity.UserInfo;
import com.wxproj.wxai.properties.Wxauthon;
import com.wxproj.wxai.service.IUserInfoService;
import com.wxproj.wxai.utils.HttpRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping()
public class UserInfoController {
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private Wxauthon wxauthon;

    private HttpRequestUtils httpRequestUtils;

    @CrossOrigin
    @GetMapping("/login")
    public R login(String code, HttpServletRequest request) throws Exception{
        String host = request.getServerName();
        int port = request.getServerPort();


        String authUrl = wxauthon.getJscodeurl()+"?appid="+wxauthon.getAppid()+
                "&secret="+wxauthon.getSecretid()+"&js_code="+code+"&grant_type=authorization_code";
        Random random = new Random();
        int randomNumber = random.nextInt(11);
        String data = httpRequestUtils.httpsGet(authUrl);
        JSONObject jsonObject = JSON.parseObject(data);
        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        UserInfo user = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("openid",openid));
        String token = "";

        if(user == null){
            String id = UUID.randomUUID().toString();
            token = JWT.create()
                    .withClaim("id",id)// 将 user id 保存到 token 里面
                    .withExpiresAt(new Date(System.currentTimeMillis() + 7*24*60 * 60 * 1000))//定义token的有效期
                    .sign(Algorithm.HMAC256(ConstantKey.JWT_TOKEN_KEY));// 加密秘钥，也可以使用用户保持在数据库中的密码字符串
            UserInfo senduser = new UserInfo();
            senduser.setAvaterUrl(randomNumber+".png");
            senduser.setId(id);
            senduser.setNickname("微信用户");
            senduser.setLastloginTime(new Date());
            senduser.setRegisterTime(new Date());
            senduser.setOpenid(openid);
            userInfoService.save(senduser);
        } else {
            token = JWT.create()
                    .withClaim("id",user.getId())// 将 user id 保存到 token 里面
                    .withExpiresAt(new Date(System.currentTimeMillis() + 7*24*60 * 60 * 1000))//定义token的有效期
                    .sign(Algorithm.HMAC256(ConstantKey.JWT_TOKEN_KEY));// 加密秘钥，也可以使用用户保持在数据库中的密码字符串
            user.setLastloginTime(new Date());
            userInfoService.updateById(user);
        }

        Map<String,String> map1 = new HashMap<>();
        map1.put("openid", openid);
        map1.put("session_key", session_key);
        map1.put("token", token);
        map1.put("nickName","微信用户");
        map1.put("avatarUrl",randomNumber+".png");
        return R.ok(map1);
    }


    @GetMapping("/listTAll")
    public R listTAll(HttpServletRequest request) throws Exception{
        String token = request.getHeader("Authorization").toString();
        Claim claim = JWT.decode(token).getClaim("id");
        String id = claim.toString().replaceAll("\"","");
        List<UserInfo> list  = userInfoService.userTextList(id);
        return R.ok(list);
    }

    @GetMapping("/listPAll")
    public R listPAll(HttpServletRequest request) throws Exception{
        String token = request.getHeader("Authorization").toString();
        Claim claim = JWT.decode(token).getClaim("id");
        String id = claim.toString().replaceAll("\"","");
        List<UserInfo> list  = userInfoService.userPicList(id);
        return R.ok(list);
    }
}
